package com.easy.reconciliation.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.easy.reconciliation.entity.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Packge com.easy.reconciliation.service
 * @Autor linNaibin
 * @Description 模仿 注册中心
 * @Version 1.0
 * @Date 2021/11/18 12:08
 */
@Component
public class Servers implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(Servers.class);

    //
    private List<ServiceInfo> service = new ArrayList<>();

    public List<ServiceInfo> getServices() {
        return this.service;
    }

    // 模仿 微服务注册
    @Bean
    public void init() {
        for (int i = 1; i < 4; i++) {
            ServiceInfo info = new ServiceInfo();
            info.setName("服务" + i);
            info.setAddress("http://127.0.0.1:8080/");
     /*       List<String> methods = new ArrayList<>();
            methods.add("heartbeat" + i);
            methods.add("execute" + i);*/

            info.setExecute("execute" + i);
            //  info.setMethods(methods);
            info.setHeartbeat("heartbeat" + i);
            //
            service.add(info);

            logger.info("服务[" + info.getName() + "]，IP[ " + info.getAddress() + "] 注册完毕。");
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        boolean con = false;
        while (con) {
            logger.info("开始发送心跳...");
            for (int i = 0; i < service.size(); i++) {
                try {
                    //
                    ServiceInfo serviceInfo = service.get(i);

                    String result = HttpUtil.get(serviceInfo.getAddress() + serviceInfo.getHeartbeat());

                    JSONObject jsonObject = JSONObject.parseObject(result);

                    if (jsonObject.getString("code").equals("0")) {
                        // 成功
                    } else {
                        service.remove(i);
                        logger.info("服务器下线了!!");
                    }

                } catch (RuntimeException e) {
                    continue;
                }
                // 5s 一次心跳
            }
            TimeUnit.SECONDS.sleep(5);

        }


    }
}
